﻿/*
 * SharePoint 2013 App Library
 *
 * Requires jQuery 1.7.1 or newer
 * Copyright (c) 2013 SharePoint Friends
 *
 * Licensed under the terms found in the Microsoft Office SharePoint 2013 App Store.
 * Fix: SPHostUrl bugfix.
 * Requries : jquery.cookie.js
 */
window.SF = window.SF || {};

window.SF.CreateQueryString = function ($) {
    // Added defined properties for IntelliSense.
    var q = {
        SPAppWebUrl: '',
        SPClientTag: '',
        SPHostLogoUrl: '',
        SPHostTitle: '',
        SPHostUrl: '',
        SPItemId: '',
        SPItemUrl: '',
        SPLanguage: '',
        SPListId: '',
        SPProductNumber: '',
        SPRecurrenceId: '',
        SPRemoteAppUrl: '',
        SPSite: '',
        SPSiteCollection: '',
        SPSiteUrl: '',
        SPSource: ''
    };
    
        var hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            if (hash[1] != null) {
                var val = decodeURIComponent(hash[1].replace(/\+/g, ' '));
                q[hash[0]] = val;
                q[hash[0].toLowerCase()] = val;
            }
        }
    var cookieName = "SPHostUrl";

    if ((document.referrer !== "") && (!document.referrer.toLowerCase().startsWith(q.SPAppWebUrl.toLowerCase()) && q.SPHostUrl)) {
        // Ensure SPAppWebUrl
        if (q.SPAppWebUrl == '')
            //if undefined, the app don't have read access to the host web
            if (!(_spPageContextInfo == undefined || _spPageContextInfo == null || _spPageContextInfo.webAbsoluteUrl == undefined))
                q.SPAppWebUrl = _spPageContextInfo.webAbsoluteUrl;

        // Ensure SPHostUrl
        
        // Fix hosturl bug

        var x = q.SPAppWebUrl.replace('://', '');
        var cookiePath = x.substr(x.indexOf('/'), x.length - x.indexOf('/'));
        $.cookie(cookieName, JSON.stringify(q), { path: cookiePath });
    }
    else {
        var cookieValue = $.cookie(cookieName);
        if (cookieValue != null) {
            q = JSON.parse(cookieValue);
        }
    }

    return q;
};


window.SF.Response = {
    QueryString: SF.CreateQueryString(jQuery)
};